const axios = require('axios');
const config = require('../config/weather');

class WeatherService {
  constructor() {
    this.amapConfig = config.amap;
    this.hefengConfig = config.hefeng;
  }

  // 获取天气数据（主用和风天气API）
  async getWeather(city) {
    try {
      return await this.getWeatherByHeFeng(city);
    } catch (err) {
      console.error('和风天气API请求失败:', err);
      throw new Error(`获取天气数据失败: ${err.message}`);
    }
  }

  // 格式化高德天气数据
  formatAMapData(data) {
    if (!data || data.status !== '1' || !data.forecasts || !data.forecasts.length) {
      throw new Error('无效的天气数据');
    }
    
    const forecast = data.forecasts[0];
    return {
      city: forecast.city,
      province: forecast.province,
      reportTime: forecast.reporttime,
      casts: forecast.casts.map(cast => ({
        date: cast.date,
        week: cast.week,
        dayWeather: cast.dayweather,
        nightWeather: cast.nightweather,
        dayTemp: cast.daytemp,
        nightTemp: cast.nighttemp,
        dayWind: cast.daywind,
        nightWind: cast.nightwind,
        dayPower: cast.daypower,
        nightPower: cast.nightpower
      }))
    };
  }

  // 使用和风天气API获取天气数据
  async getWeatherByHeFeng(city) {
    try {
      // 先获取城市ID
      const lookupParams = {
        key: this.hefengConfig.key,
        location: city
      };
      const lookupResponse = await axios.get(this.hefengConfig.cityLookupUrl, { 
        params: lookupParams,
        timeout: 5000
      });
      
      if (!lookupResponse.data || lookupResponse.data.code !== '200' || !lookupResponse.data.location || !lookupResponse.data.location.length) {
        throw new Error(lookupResponse.data.message || '城市不存在');
      }
      
      const locationId = lookupResponse.data.location[0].id;
      const weatherParams = {
        key: this.hefengConfig.key,
        location: locationId
      };
      
      const weatherResponse = await axios.get(this.hefengConfig.baseUrl, { 
        params: weatherParams,
        timeout: 5000
      });
      
      if (!weatherResponse.data || weatherResponse.data.code !== '200') {
        throw new Error(weatherResponse.data.message || '无效的天气数据');
      }
      
      return this.formatHeFengData(weatherResponse.data);
    } catch (err) {
      console.error('和风天气API请求失败:', err);
      throw new Error('获取天气数据失败: ' + (err.response?.data?.message || err.message));
    }
  }

  // 格式化和风天气数据
  formatHeFengData(data) {
    if (!data || data.code !== '200') {
      throw new Error('无效的天气数据');
    }
    
    // 实时天气数据格式化
    if (data.now) {
      return {
        city: data.refer?.sources?.[0] || '未知城市',
        updateTime: data.updateTime || new Date().toISOString(),
        weather: {
          temp: data.now.temp,
          feelsLike: data.now.feelsLike,
          text: data.now.text,
          windDir: data.now.windDir,
          windScale: data.now.windScale,
          humidity: data.now.humidity
        }
      };
    }
    
    // 预报天气数据格式化
    if (data.daily) {
      return {
        city: data.refer?.sources?.[0] || '未知城市',
        updateTime: data.updateTime || new Date().toISOString(),
        daily: data.daily.map(day => ({
          date: day.fxDate,
          tempMax: day.tempMax,
          tempMin: day.tempMin,
          textDay: day.textDay,
          textNight: day.textNight,
          windDirDay: day.windDirDay,
          windScaleDay: day.windScaleDay,
          windDirNight: day.windDirNight,
          windScaleNight: day.windScaleNight
        }))
      };
    }
    
    throw new Error('未知的天气数据格式');
  }
}

module.exports = new WeatherService();